package com.ramos.kuaixiao.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.githang.statusbar.StatusBarCompat;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.ramos.kuaixiao.App;
import com.ramos.kuaixiao.R;
import com.ramos.kuaixiao.adapter.SendOrderAdapter;
import com.ramos.kuaixiao.db.BrandInfoDB;
import com.ramos.kuaixiao.db.StoreNumDB;
import com.ramos.kuaixiao.db.UnSubmitOrderDB;
import com.ramos.kuaixiao.entity.BrandInfo;
import com.ramos.kuaixiao.entity.CartInfo;
import com.ramos.kuaixiao.entity.FindOrderDetail;
import com.ramos.kuaixiao.entity.SendOrderDetail;
import com.ramos.kuaixiao.utils.CommonLoading;
import com.ramos.kuaixiao.utils.FileUtil;
import com.ramos.kuaixiao.utils.NetUtils;
import com.ramos.kuaixiao.utils.SharedPreference;
import com.ramos.kuaixiao.utils.StringUtil;
import com.ramos.kuaixiao.utils.ToastUtils;
import com.ramos.kuaixiao.utils.Utils;

import org.apache.http.Header;
import org.apache.http.entity.ByteArrayEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


public class SendOrderActivity extends BaseActivity implements OnClickListener {
    private final static String TAG = "SendOrderActivity";
    private TextView title_text;
    LinearLayout title_reback;
    private EditText shop_name;
    private EditText shop_address;
    private EditText shop_tel;
    private EditText comment;
    TextView title_save;
    ListView shopList;
    SendOrderAdapter mAdapter;
    private Context mContext;
    CommonLoading loading;
    BrandInfoDB brandInfoDB;
    TextView tv_total;
    TextView tv_order;
    private List<BrandInfo> brandList = new ArrayList<>();
    private List<CartInfo> cartList = new ArrayList<>();
    public final static int UPLOAD_SUCCESS = 100;
    public final static int UPLOAD_FAIL = 101;
    double totalPrice;
    Spinner sendtype;
    Spinner paytype;
    ArrayAdapter adapter;
    List<SendOrderDetail> tmplist = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_order);
        mContext = this;
        initView();
        initData();
    }

    private void initView() {
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.title), false);
        brandInfoDB = new BrandInfoDB();
        title_reback = (LinearLayout) findViewById(R.id.title_reback);
        title_reback.setOnClickListener(this);

        title_text = (TextView) findViewById(R.id.title_text);
        title_text.setText("填写订单");
        title_save = (TextView) findViewById(R.id.title_save);
        title_save.setOnClickListener(this);
        shop_name = (EditText) findViewById(R.id.shop_name);
        shop_address = (EditText) findViewById(R.id.shop_address);
        shop_tel = (EditText) findViewById(R.id.shop_tel);
        comment = (EditText) findViewById(R.id.comment);
        shopList = (ListView) findViewById(R.id.shopList);

        tv_total = (TextView) findViewById(R.id.tv_total);
        tv_order = (TextView) findViewById(R.id.tv_order);
        tv_order.setOnClickListener(this);
        sendtype = (Spinner) findViewById(R.id.sendtype);
        adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.sendtype));
        adapter.setDropDownViewResource(android.R.layout.select_dialog_item);
        sendtype.setAdapter(adapter);
        paytype = (Spinner) findViewById(R.id.paytype);
        adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.paytype));
        adapter.setDropDownViewResource(android.R.layout.select_dialog_item);
        paytype.setAdapter(adapter);
    }

    private void initData() {
        try {
            brandList = brandInfoDB.findAllCustomerShop(App.mUserId);

            totalPrice = brandInfoDB.getAllMoney(brandList);
            Log.d(TAG, "brandList " + brandList.size() + " " + brandList.get(0).getCustomerName() + " totalPrice : " + totalPrice);
            cartList = brandInfoDB.getAllCart(brandList);
            mAdapter = new SendOrderAdapter(this, cartList);
            shopList.setAdapter(mAdapter);
            Utils.setListViewHeightBasedOnChildren(shopList);
            tv_total.setText("合计：" + App.df.format(Double.valueOf(totalPrice)));

            if (!StringUtil.isEmpty(brandList.get(0).getHouseName())) {
                shop_name.setText(brandList.get(0).getHouseName());
            } else {
                if (!StringUtil.isEmpty(brandList.get(0).getCustomerName())) {
                    shop_name.setText(brandList.get(0).getCustomerName());

                } else {
                    //shop_name.setText(SharedPreference.getPreferString("shop_name"));
                }
            }

            if (!StringUtil.isEmpty(brandList.get(0).getAddress())) {
                shop_address.setText(brandList.get(0).getAddress());
            } else {
                //shop_address.setText(SharedPreference.getPreferString("shop_address"));
            }

            if (!StringUtil.isEmpty(brandList.get(0).getTelphone())) {
                shop_tel.setText(brandList.get(0).getTelphone());
            } else {
                //shop_tel.setText(SharedPreference.getPreferString("shop_tel"));
            }
            App.selectName = "";
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void order() {
        tmplist.clear();
        tmplist.addAll(mAdapter.getList(brandList.get(0).getCustomerName(),brandList.get(0).getCustomerId()));
/*        if (StringUtil.isEmpty(shop_name.getText().toString())) {
            ToastUtils.show("请填写收货人");
            return;
        }
        if (StringUtil.isEmpty(shop_tel.getText().toString())) {
            ToastUtils.show("请填写联系电话");
            return;
        }
        if (StringUtil.isEmpty(shop_address.getText().toString())) {
            ToastUtils.show("请填写收货地址");
            return;
        }*/
        if(!StringUtil.isEmpty(shop_tel.getText().toString()) && !Utils.isMobileNO(shop_tel.getText().toString())){
            ToastUtils.show("请填入正确的手机号码(非固定电话)");
            return;
        }

        try {
            String url = NetUtils.INSERT_ORDER;
            loading = new CommonLoading(mContext);
            loading.setLoadText("提交订单中...");
            AsyncHttpClient client = new AsyncHttpClient(); // 创建异步请求的客户端对象
            // 创建请求参数的封装的对象
            client.setTimeout(30000);
            // 创建请求参数的封装的对象
            JSONObject jsonObject = new JSONObject();
            //jsonObject.put("userId", SharedPreference.getPreferString("id"));
            jsonObject.put("dealerId", SharedPreference.getPreferString("dealer"));
            jsonObject.put("orderSource", 2);
            jsonObject.put("phoneNum", FileUtil.getLineNum(this));
            jsonObject.put("versionName", Utils.getVersionName(this));
            jsonObject.put("custmerId", brandList.get(0).getCustomerId());
            jsonObject.put("custmerName", brandList.get(0).getCustomerName());
            jsonObject.put("houseId", brandList.get(0).getHouseId());
            jsonObject.put("houseName", brandList.get(0).getHouseName());
            jsonObject.put("businessId", SharedPreference.getPreferString("org"));
            jsonObject.put("businessName", SharedPreference.getPreferString("orgName"));
            jsonObject.put("employerId", SharedPreference.getPreferString("id"));
            jsonObject.put("employerName", SharedPreference.getPreferString("name"));
            jsonObject.put("orderTotalPrice", String.valueOf(totalPrice));
            Log.d(TAG, "orderTotalPrice " + totalPrice);
            //jsonObject.put("orderTotalPrice", 0.01);
            jsonObject.put("payType", typeToInt(paytype.getSelectedItem().toString()));
            jsonObject.put("deliveryType", typeToInt(sendtype.getSelectedItem().toString()));
            jsonObject.put("orderStatus", "SUBM");
            jsonObject.put("dstAddr", shop_address.getText().toString());
            jsonObject.put("telephone", shop_tel.getText().toString());
            jsonObject.put("communicatePeople", shop_name.getText().toString());
            jsonObject.put("comment", comment.getText().toString());
            jsonObject.put("orderDetailList", Utils.getJSONArray(mAdapter.getList(brandList.get(0).getCustomerName(),brandList.get(0).getCustomerId())));
            Log.d(TAG, "order " + url);
            Log.d(TAG, "order " + jsonObject.toString());
            ByteArrayEntity stringEntity = new ByteArrayEntity(jsonObject.toString().getBytes("UTF-8"));
            stringEntity.setContentType("application/json");
            //StringEntity stringEntity = new StringEntity(jsonObject.toString());
            // 执行post方法
            client.post(mContext, url, stringEntity, "application/json", new JsonHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONObject responseBody) {
                    loading.dismiss();
                    Log.d(TAG, "order " + responseBody.toString());
                    try {
                        if (responseBody.getInt("status") == 200) {
                            sendMessagea(UPLOAD_SUCCESS, responseBody.getString("msg"));
                            updateStore(tmplist);
                            new BrandInfoDB().deleteAllCustomerShop(brandList.get(0).getCustomerName());
                        } else {
                            //sendMessagea(UPLOAD_FAIL, "提交失败");
                            sendMessagea(UPLOAD_FAIL, responseBody.toString());
                        }
                    } catch (JSONException e) {
                        //sendMessagea(UPLOAD_FAIL, "提交失败");
                        sendMessagea(UPLOAD_FAIL, responseBody.toString());
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                    loading.dismiss();
                    //sendMessagea(UPLOAD_FAIL, "提交失败");
                    sendMessagea(UPLOAD_FAIL, errorResponse.toString());
                    throwable.printStackTrace();// 把错误信息打印出轨迹来
                }
            });
        } catch (Exception e) {
            loading.dismiss();
            //sendMessagea(UPLOAD_FAIL, "提交失败");
            sendMessagea(UPLOAD_FAIL, "提交失败");
            e.printStackTrace();
        }
    }

    private void updateStore(List<SendOrderDetail> list) {
        for(SendOrderDetail order : list){
            new StoreNumDB().updateNum(order.getProductInfoId(), order.getStoreHouseId(),order.getStoreHouseName(), order.getCalcParam(),order.getLargeUnitCount(), order.getSmallUnitCount());
        }
    }

    private int typeToInt(String s) {
        if (s.equals("货到付款")) {
            return 1;
        } else if (s.equals("在线支付")) {
            return 2;
        } else if (s.equals("信用贷款")) {
            return 3;
        } else if (s.equals("配送")) {
            return 1;
        } else if (s.equals("自提")) {
            return 2;
        } else if (s.equals("快递")) {
            return 3;
        } else {
            return 1;
        }
    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPLOAD_SUCCESS:
                    SharedPreference.setPreferString("shop_name", shop_name.getText().toString());
                    SharedPreference.setPreferString("shop_tel", shop_tel.getText().toString());
                    SharedPreference.setPreferString("shop_address", shop_address.getText().toString());
                    ToastUtils.showShort(mContext, "提交成功");
                    //brandInfoDB.deleteAllShop();
                    finish();
                    break;
                case UPLOAD_FAIL:
                    ToastUtils.showShort(mContext, msg.obj.toString() + "!请先保存，在未完成订单中继续提交");
                    break;
                default:
                    break;
            }
        }
    };

    private void sendMessagea(int iWhat, Object obj) {
        Message msg = Message.obtain();
        msg.what = iWhat;
        msg.obj = obj;
        mHandler.sendMessage(msg);
    }

    @Override
    public void onClick(View paramView) {
        switch (paramView.getId()) {
            case R.id.title_reback:
                finish();
                break;
            case R.id.tv_order:
                if (Utils.isNetworkConnected(this)) {
                    order();
                } else {
                    ToastUtils.show("当前没有网络连接，请先保存，在未完成订单中继续提交");
                }
                break;
            case R.id.title_save:
                saveLocal();
            default:
                break;
        }
    }

    private void saveLocal() {
/*        if (StringUtil.isEmpty(shop_name.getText().toString())) {
            ToastUtils.show("请填写收货人");
            return;
        }
        if (StringUtil.isEmpty(shop_tel.getText().toString())) {
            ToastUtils.show("请填写联系电话");
            return;
        }
        if (StringUtil.isEmpty(shop_address.getText().toString())) {
            ToastUtils.show("请填写收货地址");
            return;
        }*/

        if(!StringUtil.isEmpty(shop_tel.getText().toString()) && !Utils.isMobileNO(shop_tel.getText().toString())){
            ToastUtils.show("请填入正确的手机号码(非固定电话)");
            return;
        }

        FindOrderDetail order = new FindOrderDetail();
        order.setDealerId(SharedPreference.getPreferString("dealer"));
        order.setCustmerId(brandList.get(0).getCustomerId());
        order.setCustmerName(brandList.get(0).getCustomerName());
        order.setEmployerId(SharedPreference.getPreferString("id"));
        order.setEmployerName(SharedPreference.getPreferString("name"));
        order.setHouseId(brandList.get(0).getHouseId());
        order.setHouseName(brandList.get(0).getHouseName());
        order.setBusinessId(SharedPreference.getPreferString("org"));
        order.setBusinessName(SharedPreference.getPreferString("orgName"));
        order.setOrderTotalPrice(String.valueOf(totalPrice));
        order.setPayType(paytype.getSelectedItem().toString());
        order.setDeliveryType(sendtype.getSelectedItem().toString());
        order.setOrderStatus("SUBM");
        order.setDstAddr(shop_address.getText().toString());
        order.setTelephone(shop_tel.getText().toString());
        order.setCommunicatePeople(shop_name.getText().toString());
        order.setComment(comment.getText().toString());
        order.setOrderDate(Utils.getDate());
        order.setOrderDetailList(Utils.getJSONArray(mAdapter.getList(brandList.get(0).getCustomerName(),brandList.get(0).getCustomerId())).toString());
        Log.d(TAG, "Utils.getDate()：" + Utils.getDate());
        Log.d(TAG, "setOrderDetailList：" + Utils.getJSONArray(mAdapter.getList(brandList.get(0).getCustomerName(),brandList.get(0).getCustomerId())).toString());
        UnSubmitOrderDB db = new UnSubmitOrderDB();
        if (db.addUnSubmitOrder(order) == 0) {
            SharedPreference.setPreferString("shop_name", shop_name.getText().toString());
            SharedPreference.setPreferString("shop_tel", shop_tel.getText().toString());
            SharedPreference.setPreferString("shop_address", shop_address.getText().toString());
            ToastUtils.show("保存成功");
            //brandInfoDB.deleteAllShop();
            new BrandInfoDB().deleteAllCustomerShop(brandList.get(0).getCustomerName());
            finish();
        }
    }
}
